import logging
from fastapi import Query
from starlette.status import HTTP_201_CREATED
from shared_data.mock_data import FlexCommunication, mock_response
from app.schemas import *
from app.core import get_instance, AppInstance
from fastapi import Depends, Path
from fastapi import APIRouter, status
from typing import Optional
from datetime import datetime
from app.core import setting

router = APIRouter(prefix='/flex', tags=["Flex Communication"])

logger = logging.getLogger("app.api.testing_data")


@router.get("/date/{robot_ip}", status_code=status.HTTP_200_OK,
            description="Get current date in a robot", response_model=GetDateResponse,
            responses=get_expected_response_v1(GetDateResponse))
@standardize_response(statu_code=status.HTTP_200_OK)
@mock_response(FlexCommunication.instance().get_date, setting.mock_type, is_simulating=setting.use_mock)
async def get_date(robot_ip: str = Path(..., description="robot ip address", example="192.168.6.15"),
                   instance: AppInstance = Depends(get_instance)):
    flex = instance.flex_handler
    flex.connect(robot_ip)
    date = flex.get_date()
    flex.close()
    return {
        "date": date
    }


@router.post("/date", status_code=status.HTTP_200_OK, description="Update the date in a robot",
             response_model=UpdateDateResponse,
             responses=get_expected_response_v1(UpdateDateResponse))
@standardize_response(statu_code=status.HTTP_200_OK)
@mock_response(FlexCommunication.instance().update_date, setting.mock_type, is_simulating=setting.use_mock)
async def update_date(robot_ip: str = Query(..., description="Robot iP Address"),
                      date: Optional[str] = Query(default=None,
                                                  description="The date you want to set, please use formatting like"
                                                              " example, if set default, server will sync server time to "
                                                              "a robot",
                                                  examples=["2025-11-12 07:15:09"]),
                      instance: AppInstance = Depends(get_instance)):
    if date is not None:
        try:
            # 尝试解析日期格式
            datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
        except ValueError:
            raise ValueError('Date must be in format: YYYY-MM-DD HH:MM:SS, for example "2025-11-12 07:15:09"')
    flex = instance.flex_handler
    flex.connect(robot_ip)
    old_date, now_date = flex.update_date(date=date)
    flex.close()
    return {
        "old_date": old_date,
        "now_date": now_date
    }


@router.post("/recover/date/{robot_ip}", status_code=HTTP_201_CREATED,
             description="Recover date, server will not change the date, but will sudo timedatectl set-ntp true, "
                         "wait for a while, the time will be changed ",
             response_model=EmptyResponse)
@standardize_response(statu_code=status.HTTP_201_CREATED)
@mock_response(FlexCommunication.instance().recover_date, setting.mock_type, is_simulating=setting.use_mock)
async def recover_date(robot_ip: str = Path(..., description="robot ip address",
                                            example="192.168.6.15"),
                       instance: AppInstance = Depends(get_instance)):
    flex = instance.flex_handler
    flex.connect(robot_ip)
    flex.recover_date()
    flex.close()
    return {}


@router.get("/discover", status_code=status.HTTP_200_OK,
            description="Scan devices which online", response_model=DiscoverFlexResponse,
            responses=get_expected_response_v1(DiscoverFlexResponse))
@standardize_response(statu_code=status.HTTP_200_OK)
@mock_response(FlexCommunication.instance().discover_flex, setting.mock_type, is_simulating=setting.use_mock)
async def discover_flex(instance: AppInstance = Depends(get_instance)):
    flex = instance.flex_handler
    groups = flex.discover_flex()
    return {
        "numbers": len(groups),
        "flex_groups": groups
    }

@router.post("/home", status_code=status.HTTP_200_OK,
             description="Home flex", response_model=EmptyResponse,
             responses=get_expected_response_v1(EmptyResponse))
async def home(home_request: HomeRequest, instance: AppInstance = Depends(get_instance)):
    host_name = home_request.host_name
    mount = home_request.mount
    flex = instance.flex_handler
g

